package com.shuwen.gcdj.service.basics;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shuwen.gcdj.bean.basicsRepair.request.*;
import com.shuwen.gcdj.bean.basicsRepair.response.*;
import com.shuwen.gcdj.bean.dept.response.DeptListItemResp;
import com.shuwen.gcdj.bean.structure.response.StrategyInspectionItemResp;
import com.shuwen.gcdj.bean.sysDictionary.request.SysDictionaryReq;
import com.shuwen.gcdj.bean.sysDictionary.response.SysDictionaryResp;
import com.shuwen.gcdj.common.api.CommonPage;
import com.shuwen.gcdj.common.api.CommonResult;
import com.shuwen.gcdj.common.constant.Constants;
import com.shuwen.gcdj.common.util.BeanHelper;
import com.shuwen.gcdj.dto.account.InitUserDto;
import com.shuwen.gcdj.entity.*;
import com.shuwen.gcdj.entity.basics.*;
import com.shuwen.gcdj.mapper.mysql.*;
import com.shuwen.gcdj.mapper.mysql.basics.*;
import com.shuwen.gcdj.mapper.mysql.message.MessageCenterMapper;
import com.shuwen.gcdj.mapper.mysql.sysDictionary.SysDictionaryMapper;
import com.shuwen.gcdj.service.message.MsgAlarmMessageService;
import com.shuwen.gcdj.service.orderRepairorderfeedback.OrderRepairorderfeedbackServiceImpl;
import com.shuwen.gcdj.service.orderRepairorderfeedback.OrderRepairworkorderServiceImpl;
import com.shuwen.gcdj.service.sysDictionary.SysDictionaryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor
public class RepairsService extends MethodFactory {

    private final OrderRepairorderfeedbackServiceImpl orderRepairorderfeedbackService;
    private final OrderRepairorderfeedbackMapper orderRepairorderfeedbackMapper;
    private final OrderRepairorderflowMapper orderRepairorderflowMapper;
    private final OrderRepairworkorderdetailMapper orderRepairworkorderdetailMapper;
    private final OrderRepairworkorderMapper orderRepairworkorderMapper;
    private final OrderRepairworkorderServiceImpl orderRepairworkorderService;
    private final BasicsEquipmentMapper basicsEquipmentMapper;
    private final OrderRepairorderstrategyrelMapper orderRepairorderstrategyrelMapper;
    private final SysDictionaryMapper sysDictionaryMapper;
    private final OrderDelayconfigurationMapper orderDelayconfigurationMapper;
    private final SysDictionaryService sysDictionaryService;
    private final OrderDelayconfigurationService orderDelayconfigurationService;
    private final BasicsStructureMapper basicsStructureMapper;
    private final BasicsResourceMapper basicsResourceMapper;
    private final DepartmentMapper departmentMapper;
    private final StrategyInspectionitemMapper strategyInspectionitemMapper;
    private final StrategyInspectionitemtemplaterelMapper strategyInspectionitemtemplaterelMapper;
    private final TUserAccountMapper tUserAccountMapper;
    private final OrderPersonnelassignmentMapper orderPersonnelassignmentMapper;
    private final StrategyInspectionitemtemplateMapper strategyInspectionitemtemplateMapper;
    private final MsgAlarmMessageService msgAlarmMessageService;
    private final MessageCenterMapper messageCenterMapper;
    private final StrategyEquipmentstrategyrelMapper strategyEquipmentstrategyrelMapper;
    private final AccountMapper accountMapper;

    /**
     * 报修明细列表
     */
    public CommonResult<CommonPage<RepairListResp>> getList(RepairListReq req) {
        Page<RepairListResp> page = new Page<>(req.getPageNum(), req.getPageSize(), true);
        IPage<RepairListResp> allList = orderRepairworkorderMapper.getAllList(page, req);
        List<RepairListResp> res = allList.getRecords();
        Page<RepairListResp> resPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        resPage.setRecords(res);
        return CommonResult.success(CommonPage.restPage(resPage));
    }

    public static String getNewCode(OrderRepairworkorderdetail orderRepairworkorderdetail) {
        String codePrefix = "BXD";

        Long currtimestamp = System.currentTimeMillis();
        if (orderRepairworkorderdetail == null) {
            codePrefix += currtimestamp + "01";
        } else {
            String timestamp = orderRepairworkorderdetail.getOrderCode().substring(1, 10);
            if (currtimestamp.toString().equals(timestamp)) {
                codePrefix += currtimestamp + String.format("%02d", 2);
            } else {
                codePrefix += currtimestamp + "01";
            }
        }
        return codePrefix;
    }

    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> announciatorByRepair(AnnounciatorByRepairResp req) {
        if (StringUtils.isEmpty(req.getEquipmentCode())) {
            return CommonResult.failed("设备编号不能为空");
        }
        //10以内的编号补充前缀0
        String formatCode = String.format("%02d", Integer.valueOf(req.getOrderCode()));
        req.setOrderCode(formatCode);
        String commitRepairCode = "-YJ" + req.getOrderCode();
        //过滤不通过:2、拒绝:7、已完成:6等流程操作结束的数据
        List<OrderRepairworkorder> repairs = orderRepairworkorderMapper.selectList(new QueryWrapper<OrderRepairworkorder>()
                .lambda()
                .like(OrderRepairworkorder::getOrderCode, commitRepairCode)
                .notIn(OrderRepairworkorder::getState, Constants.FRP_FLOW_TWO, Constants.FRP_FLOW_SIX, Constants.FRP_FLOW_SEVEN)
                .eq(OrderRepairworkorder::getIsDelete, Constants.ZERO)
        );
        if (!CollectionUtils.isEmpty(repairs)) {
            return CommonResult.failed("该工单已存在");
        }
        BasicsEquipment equipment = basicsEquipmentMapper.selectOne(new QueryWrapper<BasicsEquipment>()
                .lambda().eq(BasicsEquipment::getCode, req.getEquipmentCode()));
        if (equipment == null) {
            return CommonResult.failed("设备不存在");
        }
        RepairStrategyDetailResp repairDetail = new RepairStrategyDetailResp();
        SysDictionaryResp major = new SysDictionaryResp();
        TUserAccount userInfo = new TUserAccount();
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.BASICS_SYS_DICTIONARY_DEPARTMENT);
        sysDictionaryReq.setParentCode(Constants.STRATEGY_INSPECTION_ITEM_INSPECTION_RESULT);
        List<SysDictionaryResp> inspectionResultList = sysDictionaryMapper.getList(sysDictionaryReq);
        sysDictionaryReq.setParentCode(Constants.STRATEGY_INSPECTION_ITEM_DISPOSAL_METHOD);
        List<SysDictionaryResp> disposalMethodList = sysDictionaryMapper.getList(sysDictionaryReq);
        sysDictionaryReq.setParentCode(Constants.BASICS_STRUCTURE_TYPE);
        List<SysDictionaryResp> structureTypeModels = sysDictionaryMapper.getList(sysDictionaryReq);
        if (!StringUtils.isEmpty(req.getStructureCode())) {
            switch (req.getDepth()) {
                case 1:
                    break;
                case 2:
                    sysDictionaryReq.setParentCode(Constants.BASICS_STRUCTURE_SECOND_NAME);
                    List<SysDictionaryResp> secondNameModels = sysDictionaryMapper.getList(sysDictionaryReq);
                    SysDictionaryResp second = secondNameModels.stream().filter(t -> t.getCode().equals(req.getStructureCode())).findFirst().orElse(null);
                    String secondName = UUID.randomUUID().toString();
                    req.setStructureId("-1");
                    if (second != null) {
                        secondName = second.getName();
                    }
                    //获取二级结构信息
                    BasicsStructure secondModel = basicsStructureMapper.selectOne(new QueryWrapper<BasicsStructure>()
                            .lambda().eq(BasicsStructure::getName, secondName)
                            .eq(BasicsStructure::getIsDelete, Constants.ZERO));
                    if (secondModel != null) {
                        //二级结构Id赋值
                        req.setStructureId(secondModel.getId());
                        //给专业和用户信息赋值
                        major = structureTypeModels.stream().filter(t -> Objects.equals(t.getValue(), secondModel.getStructureType())).findFirst().orElse(null);
                        userInfo = tUserAccountMapper.selectOne(new QueryWrapper<TUserAccount>()
                                .lambda().eq(TUserAccount::getId, secondModel.getPersonnelId()));
                    }
                    //根据二级id获取检查项关联表信息
                    List<StrategyInspectionitemtemplaterel> tempRelModels = strategyInspectionitemtemplaterelMapper.selectList(new QueryWrapper<StrategyInspectionitemtemplaterel>()
                            .lambda().eq(StrategyInspectionitemtemplaterel::getStructureId, req.getStructureId()));
                    //获取检查项
                    List<StrategyInspectionitem> inspectionitems = CollectionUtils.isEmpty(tempRelModels) ? new ArrayList<>() :
                            strategyInspectionitemMapper.selectList(new QueryWrapper<StrategyInspectionitem>()
                                    .lambda()
                                    .in(!CollectionUtils.isEmpty(tempRelModels), StrategyInspectionitem::getId,
                                            tempRelModels.stream().map(StrategyInspectionitemtemplaterel::getInspectionItemId)
                                                    .collect(Collectors.toList()))
                            );
                    List<StrategyInspectionItemResp> itemModels;
                    itemModels = BeanHelper.copyList(inspectionitems, StrategyInspectionItemResp.class);
                    //补充检查项名称描述
                    itemModels.forEach(item -> {
                        item.setDisposalMethodText(disposalMethodList.stream().filter(t -> Objects.equals(t.getValue(), item.getDisposalMethod())).findFirst().orElse(new SysDictionaryResp()).getName());
                        item.setInspectionResultText(inspectionResultList.stream().filter(t -> Objects.equals(t.getValue(), item.getInspectionResult())).findFirst().orElse(new SysDictionaryResp()).getName());
                    });
                    //报修详情信息赋值
                    repairDetail.setStructureId(req.getStructureId());
                    repairDetail.setRemark(req.getContext());
                    //报修内容（检查项信息）

                    itemModels.forEach(item -> {
                        RepairDetailStrategyResp infoResp = new RepairDetailStrategyResp();
                        infoResp.setStrategyId(item.getId());
                        infoResp.setInspectionItemId(item.getId());
                        infoResp.setInspectionItemName(item.getItemName());
                        infoResp.setDisposalMethodValue(item.getDisposalMethod());
                        infoResp.setSuggestDisposalMethod(Arrays.stream(item.getDisposalMethodText().split(";")).findFirst().orElse(""));
                        infoResp.setInspectionResultValue(item.getInspectionResult());
                        infoResp.setInspectionResult(Arrays.stream(item.getInspectionResultText().split(";")).findFirst().orElse(""));
                        repairDetail.RepairDetailStrategies.add(infoResp);
                    });
                    break;
                case 3:
                    //获取字典配置三级结构名称
                    sysDictionaryReq.setParentCode(Constants.BASICS_STRUCTURE_THIRD_NAME);
                    List<SysDictionaryResp> thirdNameModels = sysDictionaryMapper.getList(sysDictionaryReq);
                    //根据编号获取预警三级结构名称
                    SysDictionaryResp third = thirdNameModels.stream().filter(t -> t.getCode().equals(req.getStructureCode())).findFirst().orElse(null);
                    //通过三级结构名称获取模板配置信息
                    StrategyInspectionitemtemplate template = strategyInspectionitemtemplateMapper.selectOne(new LambdaQueryWrapper<StrategyInspectionitemtemplate>()
                            .eq(StrategyInspectionitemtemplate::getIsDelete, Constants.IS_DELETE_NORMAL)
                            .eq(StrategyInspectionitemtemplate::getStructureId, third.getValue())
                    );
                    if (template == null) {
                        return CommonResult.failed("未匹配到结构信息");
                    }
                    //查询模板关联的二级结构并且非模板数据(structureid为0是模板数据)
                    List<StrategyInspectionitemtemplaterel> relModels = strategyInspectionitemtemplaterelMapper.selectList(new QueryWrapper<StrategyInspectionitemtemplaterel>()
                            .lambda()
                            .eq(StrategyInspectionitemtemplaterel::getIsDelete, Constants.IS_DELETE_NORMAL)
                            .eq(StrategyInspectionitemtemplaterel::getTemplateId, template.getId())
                            .notIn(StrategyInspectionitemtemplaterel::getStructureId, Constants.ZERO)
                    );
                    //获取匹配到的第一条二级结构
                    StrategyInspectionitemtemplaterel itemRelModel = relModels.stream().findFirst().orElse(null);
                    if (template == null) {
                        return CommonResult.failed("未匹配到检查项信息");
                    }
                    //获取二级结构信息
                    BasicsStructure secondDetail = basicsStructureMapper.selectOne(new LambdaQueryWrapper<BasicsStructure>()
                            .eq(BasicsStructure::getId,itemRelModel.getStructureId())
                            .eq(BasicsStructure::getIsDelete,Constants.IS_DELETE_NORMAL)
                    );
                    if (template == null) {
                        return CommonResult.failed("未匹配到二级结构信息");
                    }
                    //二级结构Id赋值
                    req.setStructureId(secondDetail.getId());
                    //给专业和用户信息赋值
                    major = structureTypeModels.stream().filter(t -> Objects.equals(t.getValue(), secondDetail.getStructureType())).findFirst().orElse(null);
                    userInfo = tUserAccountMapper.selectOne(new QueryWrapper<TUserAccount>()
                            .lambda().eq(TUserAccount::getId, secondDetail.getPersonnelId()));
                    //获取检查项
                    List<StrategyInspectionitem> inspectionitemList = CollectionUtils.isEmpty(relModels) ? new ArrayList<>() :
                            strategyInspectionitemMapper.selectList(new QueryWrapper<StrategyInspectionitem>()
                                    .lambda()
                                    .in(!CollectionUtils.isEmpty(relModels), StrategyInspectionitem::getId,
                                            relModels.stream().map(StrategyInspectionitemtemplaterel::getInspectionItemId)
                                                    .collect(Collectors.toList()))
                            );
                    List<StrategyInspectionItemResp> itemModelList;
                    itemModelList = BeanHelper.copyList(inspectionitemList, StrategyInspectionItemResp.class);
                    //补充检查项名称描述
                    itemModelList.forEach(item -> {
                        item.setDisposalMethodText(disposalMethodList.stream().filter(t -> Objects.equals(t.getValue(), item.getDisposalMethod())).findFirst().orElse(new SysDictionaryResp()).getName());
                        item.setInspectionResultText(inspectionResultList.stream().filter(t -> Objects.equals(t.getValue(), item.getInspectionResult())).findFirst().orElse(new SysDictionaryResp()).getName());
                    });
                    //报修详情信息赋值
                    repairDetail.setStructureId(req.getStructureId());
                    repairDetail.setRemark(req.getContext());
                    //报修内容（检查项信息）

                    itemModelList.forEach(item -> {
                        RepairDetailStrategyResp infoResp = new RepairDetailStrategyResp();
                        infoResp.setStrategyId(item.getId());
                        infoResp.setInspectionItemId(item.getId());
                        infoResp.setInspectionItemName(item.getItemName());
                        infoResp.setDisposalMethodValue(item.getDisposalMethod());
                        infoResp.setSuggestDisposalMethod(item.getDisposalMethodText() != null ? Arrays.stream(item.getDisposalMethodText().split(";")).findFirst().orElse("") : "");
                        infoResp.setInspectionResultValue(item.getInspectionResult());
                        infoResp.setInspectionResult(item.getInspectionResultText() != null ? Arrays.stream(item.getInspectionResultText().split(";")).findFirst().orElse("") : "");
                        repairDetail.RepairDetailStrategies.add(infoResp);
                    });
                    break;
                default:
                    break;
            }
        }
        //添加报修
        RepairAddReq repairReq = new RepairAddReq();
        repairReq.setRepairCode(req.getOrderCode());
        repairReq.setSoursce(4);
        repairReq.setEquipmentId(equipment.getId());
        repairReq.setRepairDepartment(userInfo.getDeptId());
        repairReq.setMajor(Objects.isNull(major) ? Constants.ZERO : major.getValue());
        repairReq.setGrade(1);
        repairReq.setAreaLocation(equipment.getAreaLocation());
        RepairStructure repStructure = new RepairStructure();
        //绑定结构ID和预警内容
        repStructure.setStructureId(repairDetail.getStructureId());
        repStructure.setRemark(req.getContext());
        //绑定报修检查项
        List<RepairChilds> repChilds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(repairDetail.getRepairDetailStrategies())) {
            for (RepairDetailStrategyResp item : repairDetail.RepairDetailStrategies) {
                RepairChilds rep = new RepairChilds();
                rep.setInspectionItemId(item.getInspectionItemId());
                rep.setInspectionItemName(item.getInspectionItemName());
                if (item.getSuggestDisposalMethod().split(";").length > Constants.ZERO) {
                    rep.setSuggestDisposalMethod(item.getSuggestDisposalMethod().split(";")[Constants.ZERO]);
                }
                if (item.getInspectionResult().split(";").length > Constants.ZERO) {
                    rep.setInspectionResult(item.getInspectionResult().split(";")[Constants.ZERO]);
                }
                repChilds.add(rep);
            }
        }
        repStructure.setRepairDetailStrategies(repChilds);
        //绑定报修二级结构信息
        List<RepairStructure> repairStructureList = new ArrayList<>();
        repairStructureList.add(repStructure);
        repairReq.setRepairDetails(repairStructureList);
        //绑定登录基础信息-默认负责人
        InitUserDto userDto = new InitUserDto();
        userDto.setUserId(userInfo.getId());
        userDto.setUsername(userInfo.getShowName());
        userDto.setDeptId(userInfo.getDeptId());
        //提交报修
        String repairCode = addRepairs(repairReq, userDto).getData();

        //报修单提交成功后添加预警信息
        MsgAlarmmessage msgModel = new MsgAlarmmessage();
        msgModel.setEquipmentId(equipment.getId());
        msgModel.setEquipmentCode(equipment.getCode());
        msgModel.setEquipmentName(equipment.getName());
        msgModel.setSensorCode(req.getStructureCode());
        msgModel.setStructureId(req.getStructureId());
        msgModel.setContent(req.getContext());
        msgModel.setState(1);
        msgModel.setIsread(Constants.ZERO);
        msgModel.setOrderCode(repairCode);
        msgModel.setCreateId(Constants.ZERO.toString());
        msgModel.setCreateTime(LocalDateTime.now());
        msgModel.setUpdateId(Constants.ZERO.toString());
        msgModel.setUpdateTime(LocalDateTime.now());
        msgAlarmMessageService.save(msgModel);
        return CommonResult.success(repairCode);

    }

    /**
     * 新增报修
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> addRepairs(RepairAddReq req, InitUserDto initUserDto) {
        OrderRepairworkorderdetail orderdetail = orderRepairworkorderdetailMapper.getFistOrderdetailByCodeDesc();
        String orderCode = "";
        if (req.getRepairCode() != null && !req.getRepairCode().isEmpty()) {
            orderCode = getNewCode(orderdetail) + "-YJ" + req.getRepairCode();
        } else {
            orderCode = getNewCode(orderdetail);
        }
        //新增报修主表
        OrderRepairworkorder orderRepairworkorder = new OrderRepairworkorder();
        BasicsEquipment equipment = basicsEquipmentMapper.selectOne(new QueryWrapper<BasicsEquipment>()
                .lambda().eq(BasicsEquipment::getId, req.getEquipmentId()));
        LocalDateTime now = LocalDateTime.now();
        BeanUtils.copyProperties(req, orderRepairworkorder);
        if (equipment != null) {
            orderRepairworkorder.setEquipmentName(equipment.getName());
            orderRepairworkorder.setEquipmentNo(equipment.getCode());
        }
        orderRepairworkorder.setOrderCode(orderCode);
        orderRepairworkorder.setStartDate(now);
        orderRepairworkorder.setState(Constants.FRP_FLOW);
        orderRepairworkorder.setCreateId(initUserDto.getUserId());
        orderRepairworkorder.setUpdateId(initUserDto.getUserId());
        orderRepairworkorder.setRepairPersonName(initUserDto.getUsername());
        orderRepairworkorder.setResponsibleDepartment(initUserDto.getDeptId());
        orderRepairworkorder.setIsTardiness(Constants.IS_ACTIVE);
        orderRepairworkorderMapper.insert(orderRepairworkorder);

        //添加详情
        for (RepairStructure repairDetail : req.getRepairDetails()) {
            OrderRepairworkorderdetail orderRepairworkorderdetail = new OrderRepairworkorderdetail();
            orderRepairworkorderdetail.setRemark(repairDetail.getRemark());
            orderRepairworkorderdetail.setCode(getNewCode(orderdetail));
            orderRepairworkorderdetail.setPicture(repairDetail.getPicture());
            orderRepairworkorderdetail.setOrderCode(orderRepairworkorder.getOrderCode());
            orderRepairworkorderdetail.setOrderId(orderRepairworkorder.getId());
            orderRepairworkorderdetail.setCreateId(initUserDto.getUserId());
            orderRepairworkorderdetail.setState(orderRepairworkorder.getState());
            orderRepairworkorderdetail.setStructureId(repairDetail.getStructureId());
            orderRepairworkorderdetail.setUpdateId(initUserDto.getUserId());
            orderRepairworkorderdetail.setDisposeOperaterId(initUserDto.getUserId());
            orderRepairworkorderService.save(orderRepairworkorderdetail);
            List<OrderRepairorderfeedback> orderfeedback = new ArrayList<>();
            for (RepairChilds repairDetailStrategy : repairDetail.getRepairDetailStrategies()) {
                OrderRepairorderfeedback orderRepairorderfeedback = new OrderRepairorderfeedback();
                BeanUtils.copyProperties(repairDetailStrategy, orderRepairorderfeedback);
                orderRepairorderfeedback.setOrderCode(orderRepairworkorder.getOrderCode());
                orderRepairorderfeedback.setOrderId(orderRepairworkorder.getId());
                orderRepairorderfeedback.setState(Constants.IS_HIDDEN_NORMAL);
                orderRepairorderfeedback.setCreateId(initUserDto.getUserId());
                orderRepairorderfeedback.setUpdateId(initUserDto.getUserId());
                orderRepairorderfeedback.setSuggestDisposalMethod(repairDetailStrategy.getSuggestDisposalMethod());
                orderRepairorderfeedback.setStrategyId(repairDetailStrategy.getInspectionItemId());
                orderRepairorderfeedback.setDetailCode(orderRepairworkorderdetail.getCode());
                orderfeedback.add(orderRepairorderfeedback);
            }
            orderRepairorderfeedbackService.saveBatch(orderfeedback);

        }
        MsgOrdermessage ordermessage = new MsgOrdermessage();
        ordermessage.setOrderCode(orderRepairworkorder.getOrderCode());
        ordermessage.setOrderId(orderRepairworkorder.getId());
        ordermessage.setOrderState(orderRepairworkorder.getState());
        ordermessage.setEquipmentId(orderRepairworkorder.getEquipmentId());
        ordermessage.setEquipmentName(orderRepairworkorder.getEquipmentName());
        ordermessage.setCreateId(initUserDto.getUserId());
        ordermessage.setState(Constants.ZERO);
        ordermessage.setCreateTime(LocalDateTime.now());
        ordermessage.setUpdateId(initUserDto.getUserId());
        ordermessage.setUpdateTime(LocalDateTime.now());
        if (!CollectionUtils.isEmpty(req.getRepairDetails())) {
            ordermessage.setContent(req.getRepairDetails().stream().findFirst().get().getRemark());
            ordermessage.setRemark(ordermessage.getContent());
        }
        messageCenterMapper.insert(ordermessage);

        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        orderRepairorderflow.setOrderId(orderRepairworkorder.getId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOrderState(orderRepairworkorder.getState());
        orderRepairorderflow.setEquipmentId(orderRepairworkorder.getEquipmentId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        orderRepairorderflow.setRemark("报修");
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        return CommonResult.success(orderRepairworkorder.getOrderCode());
    }

    /**
     * 报修审核
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> getAudit(RepairAuditReq req, InitUserDto initUserDto) {
        //查询工单当前状态进行更改
        OrderRepairworkorder orderRepairworkorder = orderRepairworkorderMapper.selectById(req.getId());
        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        if (StringUtils.isEmpty(orderRepairworkorder)) {
            return CommonResult.failed(Constants.ERROR_MESSAGE);
        }
        if (req.getStatus().equals(Constants.ZERO.toString())) {
            orderRepairworkorder.setState(Constants.FRP_AUTH_TYPE_VIEW_COMMON_SECRET);
            orderRepairworkorder.setGrade(req.getGrade());
            orderRepairworkorder.setRepairDepartment(req.getDeptId());
            orderRepairorderflow.setRemark("审核通过");
        } else {
            orderRepairworkorder.setState(Constants.FRP_AUTH_OP_TYPE_REMOVE);
            orderRepairworkorder.setRemark(req.getContent());
            orderRepairworkorder.setCheckOperaterId(initUserDto.getUserId());
            orderRepairworkorder.setCheckOperaterName(initUserDto.getUsername());
            orderRepairworkorder.setEndDate(LocalDateTime.now());
            orderRepairorderflow.setRemark("审核驳回");
        }
        orderRepairworkorderMapper.updateById(orderRepairworkorder);

        //修改工单消息表记录
        MsgOrdermessage ordermessage = messageCenterMapper.selectOne(new QueryWrapper<MsgOrdermessage>()
                .lambda().eq(MsgOrdermessage::getOrderId, req.getId()));
        ordermessage.setOrderState(orderRepairworkorder.getState());
        messageCenterMapper.updateById(ordermessage);
        //对流程表进行记录添加
        orderRepairorderflow.setOrderId(req.getId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOrderState(orderRepairworkorder.getState());
        orderRepairorderflow.setEquipmentId(orderRepairworkorder.getEquipmentId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        return CommonResult.success("操作成功");
    }

    public CommonResult<Integer> saveRepairPersonnelAssignment(RepairLinkReq req, InitUserDto initUserDto) {
        orderPersonnelassignmentMapper.delete(new QueryWrapper<OrderPersonnelassignment>()
                .lambda().eq(OrderPersonnelassignment::getOrderCode, req.getOrderCode()));
        int count = Constants.ZERO;
        SysDictionaryReq sysDictionaryReq = new SysDictionaryReq();
        sysDictionaryReq.setParentCode(Constants.REPAIR_STATUS);
        List<SysDictionaryResp> repairStates = sysDictionaryMapper.getList(sysDictionaryReq);
        if (req.getUserStructure() != null && !req.getUserStructure().isEmpty()) {
            for (UserStructureReq item : req.getUserStructure()) {
                if (item.getStructureIds() != null && item.getStructureIds().size() > Constants.ZERO) {
                    for (String structureId : item.getStructureIds()) {
                        OrderPersonnelassignment orderPersonnelassignment = new OrderPersonnelassignment();
                        orderPersonnelassignment.setOrderId(req.getOrderId());
                        orderPersonnelassignment.setOrderCode(req.getOrderCode());
                        orderPersonnelassignment.setStructureId(structureId);
                        orderPersonnelassignment.setUserId(item.getUserId());
                        orderPersonnelassignment.setUserName(item.getUserName());
                        orderPersonnelassignment.setState(1);
                        count += orderPersonnelassignmentMapper.insert(orderPersonnelassignment);
                    }
                }
            }
        }
        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        orderRepairorderflow.setEquipmentId(req.getEquipmentId());
        orderRepairorderflow.setOrderState(req.getState());
        orderRepairorderflow.setEquipmentName(req.getEquipmentName());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOrderCode(req.getOrderCode());
        orderRepairorderflow.setOrderId(req.getOrderId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        SysDictionaryResp repairState = repairStates.stream().filter(t -> Objects.equals(t.getValue(), req.getState())).findFirst().orElse(null);
        if (repairState != null)
            orderRepairorderflow.setRemark("派发");
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        OrderRepairworkorder repair = orderRepairworkorderMapper.selectOne(new QueryWrapper<OrderRepairworkorder>()
                .lambda().eq(OrderRepairworkorder::getId, req.getOrderId()));
        repair.setState(req.getState());
        repair.setOrderCode(req.getOrderCode());
        orderRepairworkorderMapper.updateById(repair);
        if (Objects.equals(count, Constants.ZERO)) {
            return CommonResult.failed("分派失败");
        }

        //修改工单消息表记录
        MsgOrdermessage ordermessage = messageCenterMapper.selectOne(new QueryWrapper<MsgOrdermessage>()
                .lambda().eq(MsgOrdermessage::getOrderId, repair.getId()));
        ordermessage.setOrderState(repair.getState());
        messageCenterMapper.updateById(ordermessage);

        return CommonResult.success(1);
    }

    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> dispose(RepairDetailResp req, InitUserDto initUserDto) {
        RepairFeedbackResp repairFeedbackResp = new RepairFeedbackResp();
        repairFeedbackResp.setOrderCode(req.getJobOrderNo());
        for (RepairDetailInfoResp item : req.getRepairDetails()) {
            OrderRepairworkorderdetail detail = orderRepairworkorderdetailMapper.selectOne(new QueryWrapper<OrderRepairworkorderdetail>()
                    .lambda().eq(OrderRepairworkorderdetail::getCode, item.getCode()));
            detail.setDisposeRemark(item.getDisposeRemark());
            detail.setDisposePicture(item.getDisposeImages());
            detail.setDisposeOperaterId(item.getDisposeOperaterId());
            detail.setDisposeOperaterName(item.getDisposeOperaterName());
            orderRepairworkorderdetailMapper.updateById(detail);
            repairFeedbackResp.setDetailCode(item.getCode());
            for (RepairFeedbackInfoResp feedbackInfo : item.getRepairFeedbackInfos()) {
                repairFeedbackResp.setStrategyId(feedbackInfo.getStrategyId());
                repairFeedbackResp.setState(feedbackInfo.getState());
                repairFeedbackResp.setInspectionResult(feedbackInfo.getInspectionResult());
                repairFeedbackResp.setFeedbackType(feedbackInfo.getFeedbackType());
                repairFeedbackResp.setRemark(feedbackInfo.getRemark());
                repairFeedbackResp.setDisposalMethod(feedbackInfo.getDisposalMethod());
                repairFeedbackResp.setSuggestDisposalMethod(feedbackInfo.getSuggestDisposalMethod());
                repairFeedbackResp.setImages(feedbackInfo.getImages());
                OrderRepairorderfeedback orderRepairOrderfeedback = orderRepairorderfeedbackMapper.selectOne(new QueryWrapper<OrderRepairorderfeedback>()
                        .lambda().eq(OrderRepairorderfeedback::getOrderCode, repairFeedbackResp.getOrderCode())
                        .eq(OrderRepairorderfeedback::getDetailCode, repairFeedbackResp.getDetailCode())
                        .eq(OrderRepairorderfeedback::getStrategyId, repairFeedbackResp.getStrategyId()));
                orderRepairOrderfeedback.setState(repairFeedbackResp.getState());
                orderRepairOrderfeedback.setInspectionResult(repairFeedbackResp.getInspectionResult());
                orderRepairOrderfeedback.setFeedbackType(repairFeedbackResp.getFeedbackType());
                orderRepairOrderfeedback.setRemark(repairFeedbackResp.getRemark());
                orderRepairOrderfeedback.setDisposalMethod(repairFeedbackResp.getDisposalMethod());
                orderRepairOrderfeedback.setSuggestDisposalMethod(repairFeedbackResp.getSuggestDisposalMethod());
                orderRepairOrderfeedback.setImage(repairFeedbackResp.getImages());
                orderRepairorderfeedbackMapper.updateById(orderRepairOrderfeedback);
            }
            OrderRepairworkorder orderRepairworkorder = orderRepairworkorderMapper.selectOne(new QueryWrapper<OrderRepairworkorder>()
                    .lambda().eq(OrderRepairworkorder::getOrderCode, req.getJobOrderNo()));
            orderRepairworkorder.setState(Constants.RMP_LESSON_OWNER_ADMIN);
            orderRepairworkorderMapper.updateById(orderRepairworkorder);
            OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
            orderRepairorderflow.setOrderId(orderRepairworkorder.getId());
            orderRepairorderflow.setOperator(initUserDto.getUserId());
            orderRepairorderflow.setOrderState(orderRepairworkorder.getState());
            orderRepairorderflow.setEquipmentId(orderRepairworkorder.getEquipmentId());
            orderRepairorderflow.setOperatorName(initUserDto.getUsername());
            orderRepairorderflow.setRemark("处理");
            orderRepairorderflowMapper.insert(orderRepairorderflow);
            //修改工单消息表记录
            MsgOrdermessage ordermessage = messageCenterMapper.selectOne(new QueryWrapper<MsgOrdermessage>()
                    .lambda().eq(MsgOrdermessage::getOrderId, orderRepairworkorder.getId()));
            ordermessage.setOrderState(Constants.RMP_LESSON_OWNER_ADMIN);
            messageCenterMapper.updateById(ordermessage);
        }
        return CommonResult.success("修改成功");
    }

    /**
     * 报修派发
     */
    public CommonResult<String> getDistribute(RepairPaiReq req, InitUserDto initUserDto) {
        OrderRepairworkorder orderRepairworkorder = orderRepairworkorderMapper.selectById(req.getId());
        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        if (StringUtils.isEmpty(orderRepairworkorder)) {
            return CommonResult.failed(Constants.ERROR_MESSAGE);
        }
        orderRepairworkorder.setRepairOperaterId(req.getId());
        orderRepairworkorder.setEquipmentId(req.getEquipmentId());
        orderRepairworkorder.setState(Constants.FRP_AUTH_TYPE_VIEW_COMMON_BUS);
        orderRepairworkorderMapper.insert(orderRepairworkorder);
        //新增流程记录
        orderRepairorderflow.setOrderId(req.getOrderId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOrderState(orderRepairworkorder.getState());
        orderRepairorderflow.setEquipmentId(orderRepairworkorder.getEquipmentId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        orderRepairorderflow.setRemark("派发");
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        return CommonResult.success("派发成功");
    }

    /**
     * 报修处理
     */
    public CommonResult<String> getDispose(RepairOverReq req, InitUserDto initUserDto) {

        //根据工单id查询策略
        OrderRepairorderstrategyrel stagy = orderRepairorderstrategyrelMapper.selectOne(
                new QueryWrapper<OrderRepairorderstrategyrel>().lambda()
                        .eq(OrderRepairorderstrategyrel::getOrderId, req.getOrderId()));
        List<OrderRepairorderfeedback> order = new ArrayList<>();
        for (RepairKeyReq repairFeedbackInfo : req.getRepairFeedbackInfos()) {
            OrderRepairorderfeedback orderRepairorder = new OrderRepairorderfeedback();
            orderRepairorder.setStrategyId(stagy.getStrategyId());
            orderRepairorder.setOrderId(req.getOrderId());
            BeanUtils.copyProperties(req.getRepairFeedbackInfos(), repairFeedbackInfo);
            order.add(orderRepairorder);
        }
        //批量存入
        orderRepairorderfeedbackService.saveBatch(order);

        //将图片等信息存入详情表
        OrderRepairworkorderdetail orderRepairworkorderdetail = new OrderRepairworkorderdetail();
        BeanUtils.copyProperties(req, orderRepairworkorderdetail);
        orderRepairworkorderdetail.setDisposeOperaterId(initUserDto.getUserId());
        orderRepairworkorderdetail.setDisposeOperaterName(initUserDto.getUsername());
        orderRepairworkorderdetail.setCreateId(initUserDto.getUserId());
        orderRepairworkorderdetail.setUpdateId(initUserDto.getUserId());
        orderRepairworkorderdetailMapper.insert(orderRepairworkorderdetail);

        //新增流程记录
        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        orderRepairorderflow.setOrderId(req.getOrderId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOrderState(Constants.RMP_LESSON_OWNER_ADMIN);
        orderRepairorderflow.setEquipmentId(req.getEquipmentId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        orderRepairorderflow.setRemark("报修处理");
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        return CommonResult.success("");
    }

    public CommonResult<List<DepartmentUserTreeResp>> getDepartmentUserTree(String orderCode) {
        OrderRepairworkorder order = orderRepairworkorderMapper.selectOne(new QueryWrapper<OrderRepairworkorder>()
                .lambda().eq(OrderRepairworkorder::getOrderCode, orderCode));
        List<DeptListItemResp> depts = departmentMapper.getDeptListById(order.getRepairDepartment());
        List<RepairUserResp> users = tUserAccountMapper.getRepairUserList();
        List<DepartmentUserTreeResp> resp = new ArrayList<>();
        for (DeptListItemResp item : depts) {
            DepartmentUserTreeResp userTreeResp = new DepartmentUserTreeResp();
            userTreeResp.setName(item.getName());
            userTreeResp.setId(item.getId());
            userTreeResp.setIsDepartment(true);
            userTreeResp.childs = new ArrayList<>();
            List<RepairUserResp> childs = users.stream().filter(t -> t.getDeptId().equals(item.getId())).collect(Collectors.toList());
            for (RepairUserResp user : childs) {
                DepartmentUserTreeResp child = new DepartmentUserTreeResp();
                child.setId(user.getId());
                child.setName(user.getName());
                child.setIsDepartment(false);
                userTreeResp.childs.add(child);
            }
            resp.add(userTreeResp);
        }
        return CommonResult.success(resp);
    }

    /**
     * 报修详情
     *
     * @param id
     * @return
     */
    public CommonResult<RepairDetailResp> getRepair(String id) {
        List<DeptListItemResp> deptResult = departmentMapper.getAllList();
        SysDictionaryReq dictionaryReq = new SysDictionaryReq();
        dictionaryReq.setParentCode(Constants.REPAIR_STATUS);
        List<SysDictionaryResp> dicResult = sysDictionaryMapper.getList(dictionaryReq);
        OrderRepairworkorder repair = orderRepairworkorderMapper.selectOne(new QueryWrapper<OrderRepairworkorder>()
                .lambda().eq(OrderRepairworkorder::getId, id));
        BaseRepairResp repairResp = new BaseRepairResp();
        if (repair != null) {
            repairResp.setArea(repair.getAreaLocation().toString());
            repairResp.setDeviceCode(repair.getEquipmentNo());
            repairResp.setJobOrderSoursce(repair.getSoursce().toString());
            repairResp.setJobOrderLevel(repair.getGrade() == null ? 1 : repair.getGrade());
            repairResp.setJobOrderNo(repair.getOrderCode());
            repairResp.setStatus(repair.getState().toString());
            repairResp.setCheckOperaterId(repair.getCheckOperaterId());
            repairResp.setCheckOperaterName(repair.getCheckOperaterName());
            repairResp.setRemark(repair.getRemark());
            repairResp.setRepairPersonName(repair.getRepairPersonName());
            repairResp.setDeviceId(repair.getResponsibleDepartment());
            repairResp.setResponsibleDepartmentId(repair.getResponsibleDepartment());
            repairResp.setJobOrderId(repair.getId());
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
            if (repair.getStartDate() != null)
                repairResp.setCreateDate(pattern.format(repair.getStartDate()));
            if (repair.getEndDate() != null)
                repairResp.setEndDate(pattern.format(repair.getEndDate()));
            repairResp.setDeviceName(repair.getEquipmentName());
            repairResp.setMajor(repair.getMajor());
        }
        DeptListItemResp dept = deptResult.stream().filter(t -> Objects.equals(t.getId(), repairResp.getResponsibleDepartmentId())).findFirst().orElse(null);

        if (dept != null) {
            assert repair != null;
            repair.setResponsibleDepartment(dept.getName());
        }
        dictionaryReq.setParentCode(Constants.REPAIR_ORDER_LEVEL);
        List<SysDictionaryResp> levelDictModels = sysDictionaryMapper.getList(dictionaryReq);
        dictionaryReq.setParentCode(Constants.REPAIR_ORDER_SOURSCE);
        List<SysDictionaryResp> soursceDictModels = sysDictionaryMapper.getList(dictionaryReq);
        dictionaryReq.setParentCode(Constants.BASICS_EQUIPMENT_AREA_LOCATION);
        List<SysDictionaryResp> areaDictModels = sysDictionaryMapper.getList(dictionaryReq);
        dictionaryReq.setParentCode(Constants.ORDER_MAINTENANCEORDERDETAIL_MAJOR);
        List<SysDictionaryResp> majorDictModels = sysDictionaryMapper.getList(dictionaryReq);
        SysDictionaryResp area = areaDictModels.stream().filter(t -> Objects.equals(t.getValue(), repairResp.getJobOrderLevel())).findFirst().orElse(null);
        SysDictionaryResp dic = dicResult.stream().filter(t -> t.getValue().toString().equals(repairResp.getStatus())).findFirst().orElse(null);
        SysDictionaryResp levelDict = levelDictModels.stream().filter(t -> Objects.equals(t.getValue(), repairResp.getJobOrderLevel())).findFirst().orElse(null);
        SysDictionaryResp soursceDict = soursceDictModels.stream().filter(t -> Objects.equals(t.getValue(), repairResp.getJobOrderLevel())).findFirst().orElse(null);
        SysDictionaryResp majorDict = majorDictModels.stream().filter(t -> Objects.equals(t.getValue(), repairResp.getJobOrderLevel())).findFirst().orElse(null);
        if (area != null) {
            repairResp.setAreaText(area.getName());
        }
        if (dic != null) {
            repairResp.setStatusText(dic.getName());
        }
        if (levelDict != null) {
            repairResp.setJobOrderLevelText(levelDict.getName());
        }
        if (soursceDict != null) {
            repairResp.setJobOrderSoursceText(soursceDict.getName());
        }
        if (majorDict != null) {
            repairResp.setMajorText(majorDict.getName());
        }
        List<OrderRepairworkorderdetail> orderRepairworkorderdetails = orderRepairworkorderdetailMapper.selectList(new QueryWrapper<OrderRepairworkorderdetail>()
                .lambda().eq(OrderRepairworkorderdetail::getOrderId, id));
        List<RepairDetailInfoResp> details = new ArrayList<>();
        if (orderRepairworkorderdetails != null) {
            for (OrderRepairworkorderdetail item : orderRepairworkorderdetails) {
                RepairDetailInfoResp detail = new RepairDetailInfoResp();
                detail.setStructureId(item.getStructureId());
                detail.setRepairFeedbackInfos(new ArrayList<>());
                if (!StringUtils.isEmpty(item.getPicture())) {
                    List<BasicsResource> imagesPath = basicsResourceMapper.selectList(new QueryWrapper<BasicsResource>()
                            .lambda().in(BasicsResource::getId, item.getPicture().split(",")));
                    if (imagesPath != null && !imagesPath.isEmpty()) {
                        detail.setImages(imagesPath.stream().map(BasicsResource::getPath).collect(Collectors.joining(",")));
                    }
                }
                if (!StringUtils.isEmpty(item.getDisposePicture())) {
                    List<BasicsResource> disposeImagesPath = basicsResourceMapper.selectList(new QueryWrapper<BasicsResource>()
                            .lambda().in(BasicsResource::getId, Arrays.stream(item.getDisposePicture().split(",")).collect(Collectors.toList())));
                    if (disposeImagesPath != null && !disposeImagesPath.isEmpty()) {
                        detail.setDisposeImages(disposeImagesPath.stream().map(BasicsResource::getPath).collect(Collectors.joining(",")));
                    }
                }
                detail.setDisposeRemark(item.getDisposeRemark());
                detail.setRemark(item.getRemark());
                detail.setCode(item.getCode());
                detail.setDisposeOperaterId(item.getDisposeOperaterId());
                detail.setDisposeOperaterName(item.getDisposeOperaterName());
                details.add(detail);
            }
        }
        dictionaryReq.setParentCode(Constants.STRATEGY_INSPECTION_ITEM_DISPOSAL_METHOD);
        List<SysDictionaryResp> dicDisposalMethodResult = sysDictionaryMapper.getList(dictionaryReq);
        for (RepairDetailInfoResp item : details) {
            BasicsStructure structure = basicsStructureMapper.selectOne(new QueryWrapper<BasicsStructure>()
                    .lambda().eq(BasicsStructure::getId, item.getStructureId()));
            if (structure != null) {
                BasicsStructure basicsStructure = basicsStructureMapper.selectOne(new QueryWrapper<BasicsStructure>()
                        .lambda().eq(BasicsStructure::getId, structure.getParentId()));
                item.setStructureName(structure.getName());
                if (basicsStructure != null) {
                    item.setParentStructureId(basicsStructure.getId());
                    item.setParentStructureName(basicsStructure.getName());
                }
            }

        }
        if (repairResp.getDeviceCode() != null) {
            BasicsEquipment equipment = basicsEquipmentMapper.selectOne(new QueryWrapper<BasicsEquipment>()
                    .lambda().eq(BasicsEquipment::getCode, repairResp.getDeviceCode().split("-")[Constants.ZERO]));
            if (equipment != null) {
                repairResp.setDeviceId(equipment.getId());
            }
        }
        RepairDetailResp repairDetail = new RepairDetailResp();
        if (repairResp.getJobOrderId() == null) {
            return CommonResult.failed("找不到工单信息");
        }
        BeanUtils.copyProperties(repairResp, repairDetail);
        repairDetail.setRepairDetails(details);
        for (RepairDetailInfoResp item : repairDetail.getRepairDetails()) {
            List<RepairFeedbackInfoResp> feedback = orderRepairorderfeedbackMapper.getRepairFeedList(item.getCode());
            item.setRepairFeedbackInfos(feedback);
            for (RepairFeedbackInfoResp feedbackInfo : item.getRepairFeedbackInfos()) {
                feedbackInfo.setStructureId(item.getStructureId());
                feedbackInfo.setStructureName(item.getStructureName());
                StrategyInspectionitem inspectItem = strategyInspectionitemMapper.selectOne(new QueryWrapper<StrategyInspectionitem>()
                        .lambda().eq(StrategyInspectionitem::getId, feedbackInfo.getStrategyId()));
                if (inspectItem != null) {
                    feedbackInfo.setStrategyName(inspectItem.getItemName());
                    feedbackInfo.setCheckProject(inspectItem.getItemName());
                    SysDictionaryResp disposelMethod = dicDisposalMethodResult.stream().filter(t -> Objects.equals(t.getValue(), inspectItem.getDisposalMethod())).findFirst().orElse(null);
                    if (disposelMethod != null) {
                        feedbackInfo.setDisposalMethods(Arrays.stream(disposelMethod.getName().split(";")).collect(Collectors.toList()));
                    }
                    SysDictionaryResp inspection = dicDisposalMethodResult.stream().filter(t -> Objects.equals(t.getValue(), inspectItem.getInspectionResult())).findFirst().orElse(null);
                    if (inspection != null) {
                        feedbackInfo.setInspectionResults(Arrays.stream(inspection.getName().split(";")).collect(Collectors.toList()));
                    }
                    feedbackInfo.setSuggestDisposalMethod(feedbackInfo.getSuggestDisposalMethod());
                }
            }
        }
        return CommonResult.success(repairDetail);
    }

    /**
     * 报修验收
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> getAcceptance(RepairAuditReq req, InitUserDto initUserDto) {
        //查询工单当前状态进行更改
        OrderRepairworkorder orderRepairworkorder = orderRepairworkorderMapper.selectById(req.getId());
        OrderRepairorderflow orderRepairorderflow = new OrderRepairorderflow();
        if (StringUtils.isEmpty(orderRepairworkorder)) {
            return CommonResult.failed(Constants.ERROR_MESSAGE);
        }
        if (req.getStatus().equals(Constants.ZERO.toString())) {
            orderRepairworkorder.setState(Constants.RMP_LESSON_OWNER_VIEW);
            orderRepairworkorder.setCheckOperaterId(initUserDto.getUserId());
            orderRepairworkorder.setEndDate(LocalDateTime.now());
            orderRepairworkorder.setCheckOperaterName(initUserDto.getUsername());
            orderRepairorderflow.setRemark("验收通过");
        } else {
            orderRepairworkorder.setState(Constants.RMP_LESSON_RECEIVE_APPLY_MSG);
            orderRepairworkorder.setRemark(req.getContent());
            orderRepairworkorder.setCheckOperaterId(initUserDto.getUserId());
            orderRepairworkorder.setCheckOperaterName(initUserDto.getUsername());
            orderRepairworkorder.setEndDate(LocalDateTime.now());
            orderRepairorderflow.setRemark("验收驳回");
        }
        orderRepairworkorderMapper.updateById(orderRepairworkorder);

        //修改工单消息表记录
        MsgOrdermessage ordermessage = messageCenterMapper.selectOne(new QueryWrapper<MsgOrdermessage>()
                .lambda().eq(MsgOrdermessage::getOrderId, orderRepairworkorder.getId()));
        ordermessage.setOrderState(orderRepairworkorder.getState());
        messageCenterMapper.updateById(ordermessage);

        //对流程表进行记录添加

        orderRepairorderflow.setOrderId(req.getId());
        orderRepairorderflow.setOperator(initUserDto.getUserId());
        orderRepairorderflow.setOrderState(orderRepairworkorder.getState());
        orderRepairorderflow.setEquipmentId(orderRepairworkorder.getEquipmentId());
        orderRepairorderflow.setOperatorName(initUserDto.getUsername());
        orderRepairorderflowMapper.insert(orderRepairorderflow);
        return CommonResult.success("操作成功");
    }

    /**
     * 查看报修明细
     */
    public CommonResult<RepairDetailAllResp> getDetails(String id) {
        RepairDetailAllResp repairDetailsResp = new RepairDetailAllResp();


        //根id查寻订单
        OrderRepairworkorder orderRepairworkorder = orderRepairworkorderMapper.selectOne(
                new QueryWrapper<OrderRepairworkorder>().lambda()
                        .eq(OrderRepairworkorder::getIsDelete, Constants.IS_DELETE_NORMAL)
                        .eq(OrderRepairworkorder::getId, id));
        SysDictionary sysType = sysDictionaryMapper.selectOne(
                new QueryWrapper<SysDictionary>().lambda()
                        .eq(SysDictionary::getValue, orderRepairworkorder.getMajor())
                        .eq(SysDictionary::getParentCode, Constants.BASICS_STRUCTURE_TYPE));
        SysDictionary sysDictionary = sysDictionaryMapper.selectOne(
                new QueryWrapper<SysDictionary>().lambda()
                        .eq(SysDictionary::getValue, orderRepairworkorder.getGrade())
                        .eq(SysDictionary::getParentCode, Constants.REPAIR_ORDER_LEVEL));
        SysDictionary sysBao = sysDictionaryMapper.selectOne(
                new QueryWrapper<SysDictionary>().lambda()
                        .eq(SysDictionary::getValue, orderRepairworkorder.getSoursce())
                        .eq(SysDictionary::getParentCode, Constants.REPAIR_ORDER_SOURSCE));
        BeanUtils.copyProperties(orderRepairworkorder, repairDetailsResp);
        repairDetailsResp.setMajor(sysType.getName());
        repairDetailsResp.setGrade(sysDictionary.getName());
        repairDetailsResp.setSoursce(sysBao.getName());

        //根据详情查询绑定的二级部件
        List<OrderRepairworkorderdetail> orderRepairworkorderdetails = orderRepairworkorderdetailMapper.selectList(
                new QueryWrapper<OrderRepairworkorderdetail>().lambda()
                        .eq(OrderRepairworkorderdetail::getOrderId, id));
        List<RepairStructureResp> repairStructures = BeanHelper.copyList(orderRepairworkorderdetails, RepairStructureResp.class);
        for (RepairStructureResp orderRepairworkorderdetail : repairStructures) {
            //获取三级部件的信息
            BasicsStructure basicsStructure = basicsStructureMapper.selectById(orderRepairworkorderdetail.getStructureId());
            if (!StringUtils.isEmpty(basicsStructure)) {
                orderRepairworkorderdetail.setStructureName(basicsStructure.getName());
            }
            //获取部件下检查项信息
            List<OrderRepairorderfeedback> orderRepairorderfeedbacks = orderRepairorderfeedbackMapper.selectList(
                    new QueryWrapper<OrderRepairorderfeedback>().lambda()
                            .eq(OrderRepairorderfeedback::getOrderId, id));
            List<RepairChilds> repairChilds = BeanHelper.copyList(orderRepairorderfeedbacks, RepairChilds.class);
            orderRepairworkorderdetail.setRepairDetailStrategies(repairChilds);
        }
        repairDetailsResp.setRepairDetails(repairStructures);
        return CommonResult.success(repairDetailsResp);
    }

    /**
     * 报修明细-报修流程查看
     */
    public CommonResult<List<RepairPeopleReq>> getFlow(String id) {

        List<OrderRepairorderflow> orderRepairorderflows = orderRepairorderflowMapper.selectList(
                new QueryWrapper<OrderRepairorderflow>().lambda()
                        .eq(OrderRepairorderflow::getOrderId, id));
        List<RepairPeopleReq> repairPeopleReqs = BeanHelper.copyList(orderRepairorderflows, RepairPeopleReq.class);
        repairPeopleReqs.forEach(repairPeopleReq ->
                repairPeopleReq.setOperator(orderRepairorderflows.stream().filter(e -> e.getId().equals(repairPeopleReq.getId())).findFirst().orElse(new OrderRepairorderflow()).getOperatorName()));
        return CommonResult.success(repairPeopleReqs.stream().sorted(Comparator.comparing(RepairPeopleReq::getCreateTime)).collect(Collectors.toList()));
    }

    /**
     * 拖期配置-新增
     */
    public CommonResult<RepaorResp> tardinessAdd(RepairTardinessReq req) {
        OrderDelayconfiguration configuration = new OrderDelayconfiguration();
        BeanUtils.copyProperties(req, configuration);
        configuration.setConfigId(Constants.ZERO);
        configuration.setDelayType(Constants.ZERO);
        configuration.setSource(Constants.ZERO);
        configuration.setWorkOrderLevel(req.getWorkOrderLevel());
        orderDelayconfigurationMapper.insert(configuration);
        RepaorResp repaorResp = new RepaorResp();
        repaorResp.setId(configuration.getId());
        return CommonResult.success(repaorResp);
    }

    /**
     * 拖期配置-修改
     */
    public CommonResult<String> tardinessUpdate(RepairTardinessReq req) {
        OrderDelayconfiguration configuration = orderDelayconfigurationMapper.selectById(req.getId());
        if (StringUtils.isEmpty(configuration)) {
            return CommonResult.failed("拖期不存在");
        }
        configuration.setCycle(req.getCycle());
        orderDelayconfigurationMapper.updateById(configuration);
        return CommonResult.success("修改成功");
    }


    /**
     * 拖期配置-删除
     */
    public CommonResult<String> tardinessDelete(String id) {
        OrderDelayconfiguration configuration = orderDelayconfigurationMapper.selectById(id);
        if (StringUtils.isEmpty(configuration)) {
            return CommonResult.failed("拖期不存在");
        }
        configuration.setIsDelete(Constants.IS_DELETE_YES);
        orderDelayconfigurationMapper.updateById(configuration);
        return CommonResult.success("删除成功");
    }

    public List<RepairIndexPageResp> getRepairIndexPage(String equipmentId) {
        return orderRepairworkorderMapper.getRepairIndexPage(equipmentId);
    }

    public StrategyRelInfoResp getStategyIdByEquipmentId(String equipmentId) {

        return orderRepairworkorderMapper.getStrategyEquipmentRelOne(equipmentId);
    }

    public List<OrderDelayconfigurationIResp> getDelayList(Integer type) {
        List<OrderDelayconfigurationIResp> resp = new ArrayList<>();
        if (Objects.equals(type, Constants.ONE)) {
            //工单来源
            List<SysDictionary> sourceModels = sysDictionaryService.list(new LambdaQueryWrapper<SysDictionary>()
                    .eq(SysDictionary::getIsDelete, Constants.ZERO)
                    .eq(SysDictionary::getParentCode, Constants.ORDER_DELAYCONFIGURATION_SOURCE)
            );
            List<Integer> sources = sourceModels.stream().map(SysDictionary::getValue).collect(Collectors.toList());
            List<OrderDelayconfiguration> models = orderDelayconfigurationService.list(new LambdaQueryWrapper<OrderDelayconfiguration>()
                    .in(OrderDelayconfiguration::getSource, sources));
            for (OrderDelayconfiguration model : models) {
                OrderDelayconfigurationIResp entity = new OrderDelayconfigurationIResp();
                BeanHelper.copyProperties(model, entity);
                resp.add(entity);
            }
            for (OrderDelayconfigurationIResp od : resp) {
                List<SysDictionary> sd = sourceModels.stream().filter(x -> x.getValue().equals(od.source)).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(sd)) {
                    od.setStrSource(sd.get(Constants.ZERO).getName());
                }
            }
        } else if (Objects.equals(type, Constants.TWO)) {
            //工单等级
            List<SysDictionary> levelModels = sysDictionaryService.list(new LambdaQueryWrapper<SysDictionary>()
                    .eq(SysDictionary::getIsDelete, Constants.ZERO)
                    .eq(SysDictionary::getParentCode, Constants.REPAIR_ORDER_LEVEL)
            );
            List<Integer> levels = levelModels.stream().map(SysDictionary::getValue).collect(Collectors.toList());
            List<OrderDelayconfiguration> models = orderDelayconfigurationService.list(new LambdaQueryWrapper<OrderDelayconfiguration>()
                    .in(OrderDelayconfiguration::getWorkOrderLevel, levels));
            for (OrderDelayconfiguration model : models) {
                OrderDelayconfigurationIResp entity = new OrderDelayconfigurationIResp();
                BeanHelper.copyProperties(model, entity);
                resp.add(entity);
            }
            for (OrderDelayconfigurationIResp od : resp) {
                List<SysDictionary> sd = levelModels.stream().filter(x -> x.getValue().equals(od.getWorkOrderLevel())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(sd)) {
                    od.setStrWorkOrderLevel(sd.get(Constants.ZERO).getName());
                }
            }
        }
        return resp;
    }

    public RepairEarlyWarningStatisticsResp getRepairEarlyWarningStatistics(String equipmentcode) {
        RepairEarlyWarningStatisticsResp resp = new RepairEarlyWarningStatisticsResp();
        List<SysDictionaryResp> dictModels = sysDictionaryService.getChildByParentCode(Constants.SENSOR_INFORMATION_STATISTICS);
        SysDictionaryResp dictModel = null;
        if (!CollectionUtils.isEmpty(dictModels)) {
            dictModel = dictModels.stream().filter(dict -> dict.getOperateObject().equals(equipmentcode)).findFirst().orElse(null);
        }
        List<MsgAlarmmessage> msgModels = msgAlarmMessageService.list();
        List<String> repairCodes = new ArrayList<>();
        if (!CollectionUtils.isEmpty(msgModels)) {
            repairCodes = msgModels.stream().map(MsgAlarmmessage::getOrderCode).collect(Collectors.toList());
        }
        List<OrderRepairworkorder> repairModels = new ArrayList<>();
        if (!CollectionUtils.isEmpty(repairCodes)) {
            repairModels = orderRepairworkorderMapper.selectList(
                    new LambdaQueryWrapper<OrderRepairworkorder>()
                            .eq(OrderRepairworkorder::getIsDelete, Constants.ZERO)
                            .in(OrderRepairworkorder::getOrderCode, repairCodes)
            );
        }
        int normalNum = dictModel == null ? Constants.ZERO : dictModel.getValue();
        int disposeNum = Constants.ZERO;
        int warnNum = Constants.ZERO;
        if (!CollectionUtils.isEmpty(repairModels)) {
            List<OrderRepairworkorder> noCloseRepairs = repairModels.stream().filter(x -> !x.getState().equals(Constants.FRP_FLOW_SEVEN)&&!x.getState().equals(Constants.FRP_FLOW_SIX)&&!x.getState().equals(Constants.FRP_FLOW_TWO)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(noCloseRepairs)) {
                disposeNum = (int) noCloseRepairs.stream().filter(x -> !x.getState().equals(Constants.FRP_FLOW)).count();
                warnNum = (int) noCloseRepairs.stream().filter(x -> x.getState().equals(Constants.FRP_FLOW)).count();
            }
        }
        resp.setNormal(normalNum - disposeNum - warnNum);
        resp.setAwaitDispose(disposeNum);
        resp.setWarning(warnNum);
        return resp;
    }

    /**
     * 根据报修工单编号获取工单状态和流程信息
     * @param repairCode
     * @return
     */
    public CommonResult<RepairProcessResults> getRepairStatusAndFlowDetailByRepairCode(String repairCode)
    {
        RepairProcessResults repairProcessResults = new RepairProcessResults();
        //验证是否参数正常
        if (StringUtils.isEmpty(repairCode)){
            return CommonResult.failed("报修编号不可为空");
        }
        //根据编号获取主报修单信息
        OrderRepairworkorder repairworkorder = orderRepairworkorderMapper.selectOne(new LambdaQueryWrapper<OrderRepairworkorder>()
                .eq(OrderRepairworkorder::getIsDelete,Constants.IS_DELETE_NORMAL)
                .eq(OrderRepairworkorder::getOrderCode,repairCode)
                .orderByDesc(OrderRepairworkorder::getCreateTime)
        );
        if (repairworkorder == null){
            return CommonResult.failed("未找到该工单信息");
        }
        //根据编号获取主报修单信息
        OrderRepairworkorderdetail repairworkorderDetail = orderRepairworkorderdetailMapper.selectOne(new LambdaQueryWrapper<OrderRepairworkorderdetail>()
                .eq(OrderRepairworkorderdetail::getIsDelete,Constants.IS_DELETE_NORMAL)
                .eq(OrderRepairworkorderdetail::getOrderCode,repairCode)
                .orderByDesc(OrderRepairworkorderdetail::getCreateTime)
        );
        if (repairworkorderDetail == null){
            return CommonResult.failed("未找到该工单详情信息");
        }
        //查询所有用户
        List<Account> accountList = accountMapper.selectList(new QueryWrapper<Account>()
                .lambda().eq(Account::getIsDelete,Constants.IS_DELETE_NORMAL));
        //获取工单状态字典配置
        SysDictionaryReq dictReq = new SysDictionaryReq();
        dictReq.setParentCode(Constants.REPAIR_STATUS);
        List<SysDictionaryResp> repairStatusList = sysDictionaryMapper.getList(dictReq);
        //获取工单状态信息
        SysDictionaryResp localStatus = repairStatusList.stream().filter(status->status.getValue().equals(repairworkorder.getState())).findFirst().orElse(null);

        repairProcessResults.setRepairCode(repairworkorder.getOrderCode());
        repairProcessResults.setState(localStatus.getValue());
        repairProcessResults.setStateContent(localStatus.getName());
        repairProcessResults.setEquipmentName(repairworkorder.getEquipmentName());
        repairProcessResults.setOperatorName(accountList.stream().filter(x->x.getId().equals(repairworkorder.getCreateId())).findFirst().orElse(new Account()).getShowName());

        //根据工单ID获取该条工单的流程(按时间正序)
        List<OrderRepairorderflow> flowList = orderRepairorderflowMapper.selectList(new QueryWrapper<OrderRepairorderflow>()
                .lambda()
                .eq(OrderRepairorderflow::getOrderId,repairworkorder.getId())
                .eq(OrderRepairorderflow::getIsDelete,Constants.IS_DELETE_NORMAL)
                .orderByAsc(OrderRepairorderflow::getCreateTime)
        );
        List<RepairProcessDetails> repairProcessDetails = new ArrayList<>();
        //流程2(审批不通过)、7(验收需整改)从主表取出remark的反馈信息到反馈内容字段
        //流程5(待验收)从明细表取dispose_remark内容到反馈字段
        for (OrderRepairorderflow flow : flowList) {
            RepairProcessDetails processDetails = new RepairProcessDetails();
            if (flow.getOrderState().equals(Constants.FRP_FLOW_TWO) || flow.getOrderState().equals(Constants.FRP_FLOW_SEVEN))
            {
                processDetails.setDescription(repairworkorder.getRemark());
            }
            if (flow.getOrderState().equals(Constants.FRP_FLOW_FIVE))
            {
                processDetails.setDescription(repairworkorderDetail.getDisposeRemark());
            }
            processDetails.setAction(flow.getRemark());
            processDetails.setOperator(flow.getOperatorName());
            processDetails.setOperationTime(flow.getCreateTime());
            repairProcessDetails.add(processDetails);
        }
        repairProcessResults.setRepairProcessDetails(repairProcessDetails);
        return CommonResult.success(repairProcessResults);
    }

    public SysDictionaryResp dictionaryRespValueToName(List<SysDictionaryResp> dictionaryRespList,Integer value){
        SysDictionaryResp dictionaryResp = dictionaryRespList.stream().filter(x->x.getValue().equals(value)).findFirst().orElse(null);
        return dictionaryResp;
    }

}
